import { Module } from 'vuex'
import { ObjectBaseAll, ObjectString } from '@/types/type-common'
import { removeStorage, setStorage } from '@/utils/auth'
import { login } from '@/api/login'
import router, { routes, defaultRoutes } from '@/router'
import { RouteRecordRaw } from 'vue-router'
import hooks from '@/hooks'
import { getUserInfo } from '@/api/user'

interface State {
  userInfo: ObjectString
  asyncRoutes: RouteRecordRaw[]
  routes: RouteRecordRaw[]
}

interface Menu {
  name: string
}

const filterRoutes = (routes: RouteRecordRaw[], menus: Menu[]) => {
  const arr = routes.filter(item => {
    if (menus.find(menu => menu.name === item.name)) {
      if (item.children?.length) {
        item.children = filterRoutes(item.children, menus)
        if (item.children?.length) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    } else {
      return false
    }
  })

  return arr
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user: Module<any, State> = {
  state: {
    userInfo: {},
    routes: [],
    asyncRoutes: []
  },
  mutations: {
    SET_USER_INFO(state, info) {
      state.userInfo = info
    },
    SET_ASYNC_ROUTES(state, asyncRoutes) {
      state.asyncRoutes = asyncRoutes
    },
    SET_ROUTES(state, routes) {
      state.routes = routes
    }
  },
  actions: {
    login({ commit }, data: ObjectString) {
      login(data).then((res: ObjectString) => {
        setStorage('token', res.token)
        hooks.notification('登录成功', '成功', 'success')
        router.push({ name: 'home_overview' })
      })
    },
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(
          (res: any[]) => {
            console.log('res', '-------', res)
            commit('SET_USER_INFO', res)
            resolve(res)
          },
          err => {
            reject(err)
          }
        )
      })
    },
    filterRoutes({ commit }, userInfo) {
      return new Promise(resolve => {
        let asyncRoutes: RouteRecordRaw[]
        if (process.env.VUE_APP_OPEN_PERMISSION === 'true') {
          const menus: Menu[] = userInfo.menus
          asyncRoutes = filterRoutes(routes, menus)
        } else {
          asyncRoutes = routes
        }
        commit('SET_ASYNC_ROUTES', asyncRoutes)

        const userRoutes: RouteRecordRaw[] = defaultRoutes.concat(asyncRoutes)
        console.log('-------------- userRoutes: ', userRoutes)
        commit('SET_ROUTES', userRoutes)
        resolve(asyncRoutes)
      })
    },
    logout({ commit }) {
      // 调登出接口
      removeStorage('token')
      commit('SET_USER_INFO', {})
      location.reload()
    }
  }
}

export { user, State }
export default user
